import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/services.dart';
import 'package:image/image.dart' as img;
import 'package:yzcreator/image_file.dart';

class YZHomePage extends StatefulWidget {
  const YZHomePage({super.key});

  @override
  State<YZHomePage> createState() => _YZHomePageState();
}

class _YZHomePageState extends State<YZHomePage> {
  // 选择的印章图片文件
  File? selectFile;

  // 抠图后的图片
  img.Image? cropedImage;

  @override
  Widget build(BuildContext context) {
    return PlatformMenuBar(
      menus: [
        PlatformMenu(
          label: '印章工匠',
          menus: [
            PlatformMenuItemGroup(
              members:[
                PlatformMenuItem(
                  label: 'About',
                  onSelected: () {
                    // _handleMenuSelection(MenuSelection.about);
                  },
                ),
              ],
            ),
            PlatformMenuItemGroup(
              members: [
                PlatformMenuItem(
                  onSelected: () {
                    // _handleMenuSelection(MenuSelection.showMessage);
                  },
                  shortcut: CharacterActivator('m'),
                  label: 'Show Message',
                ),
                PlatformMenu(
                  label: 'Messages',
                  menus: <PlatformMenuItem>[
                    PlatformMenuItem(
                      label: 'I am not throwing away my shot.',
                      shortcut: SingleActivator(LogicalKeyboardKey.digit1,
                          meta: true),
                      onSelected: () {
                        setState(() {
                          // _message = 'I am not throwing away my shot.';
                        });
                      },
                    ),
                    PlatformMenuItem(
                      label:
                          "There's a million things I haven't done, but just you wait.",
                      shortcut: SingleActivator(LogicalKeyboardKey.digit2,
                          meta: true),
                      onSelected: () {
                        setState(() {
                          // _message =
                          // "There's a million things I haven't done, but just you wait.";
                        });
                      },
                    ),
                  ],
                ),
              ],
            ),
            if (PlatformProvidedMenuItem.hasMenu(
                PlatformProvidedMenuItemType.quit))
              PlatformProvidedMenuItem(
                  type: PlatformProvidedMenuItemType.quit),
          ],
        ),
      ],
      child: Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextButton(
                onPressed: _selectFile,
                child: Text("选择印章"),
              ),
              selectFile == null
                  ? Text("未选择印章")
                  : Image.file(
                      selectFile!,
                      width: 100,
                      height: 100,
                    ),
              TextButton(
                onPressed: _crop,
                child: Text("抠图"),
              ),
              TextButton(
                onPressed: _export,
                child: Text("导出"),
              ),
              cropedImage == null
                  ? Text("未处理")
                  : Image.memory(cropedImage!.getBytes()),
            ],
          ),
        ),
      ),
    );
  }

  // 打开文件
  _selectFile() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles();
    if (result != null) {
      File file = File(result.files.single.path!);
      if (file.isImage) {
        setState(() {
          selectFile = file;
        });
      } else {
        _showDialog(title: "格式错误", content: "请选择PNG、JPG、JPEG格式的图片");
      }
    }
  }

  // 提示框
  _showDialog({required String title, required String content}) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(title),
        content: Text(content),
        actions: [
          TextButton(
            child: Text("确定"),
            onPressed: () => Navigator.of(context).pop(), // 关闭对话框
          ),
        ],
      ),
    );
  }

  // 导出
  _export() async {
    String? outputFile = await FilePicker.platform
        .saveFile(dialogTitle: "导出印章", type: FileType.image);
    if (outputFile != null) {
      try {
        img.Image? image = await img.decodeImageFile(selectFile!.path);
        // img.Image transparentImage =
        //     await colorTransparent(image!, 255, 255, 255);
        File returnedFile = File(outputFile);
        await returnedFile.writeAsBytes(image!.getBytes());
      } catch (e) {
        debugPrint(e.toString());
      }
    }
  }

  _crop() async {
    if (selectFile == null) {
      return;
    }
    img.Image? image = await img.decodeImageFile(selectFile!.path);
    img.Image transparentImage = await colorTransparent(image!, 255, 255, 255);
    setState(() {
      cropedImage = transparentImage;
    });
  }

  Future<Uint8List> removeWhiteBackground(Uint8List bytes) async {
    img.Image image = img.decodeImage(bytes)!;
    img.Image transparentImage = await colorTransparent(image, 255, 255, 255);
    var newPng = img.encodePng(transparentImage);
    return newPng;
  }

  Future<img.Image> colorTransparent(
      img.Image src, int red, int green, int blue) async {
    var pixels = src.getBytes();
    for (int i = 0, len = pixels.length; i < len; i += 4) {
      if (pixels[i] == red && pixels[i + 1] == green && pixels[i + 2] == blue) {
        pixels[i + 3] = 0;
      }
    }

    return src;
  }
}
